package cn.edu.hust.cm.lib;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;

/**
 * 对小的二进制文件进行包装, 方便进行十六进制的显示. 注意, 如果用于大的二进制文件, 可能存在性能问题及内存占用过高的问题
 * 
 * @author 陈明
 * 
 */
public class BinFileWrapper extends TextFileWrapper {

	public BinFileWrapper(File parent, String child) throws IOException {
		super(parent, child);
	}

	public BinFileWrapper(InputStream in) throws IOException {
		super(in);
	}

	public BinFileWrapper(String parent, String child) throws IOException {
		super(parent, child);
	}

	public BinFileWrapper(String pathname) throws IOException {
		super(pathname);
	}

	public BinFileWrapper(URI uri) throws IOException {
		super(uri);
	}

	@Override
	protected void init() throws IOException {
		// TODO Auto-generated method stub
		// super.init();

		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				file));
		lines = new ArrayList<String>();
		try {
			byte[] data = IOUtils.readBytes(bis);
			dataToLines(data);
		} catch (IOException e) {
			JavaLog.e(e.getMessage());
			throw e;
		} finally {
			IOUtils.close(bis);
		}

	}

	@Override
	protected void init2() throws IOException {
		// TODO Auto-generated method stub
		// super.init2();
		lines = new ArrayList<String>();
		byte[] data = IOUtils.readBytes(in);

		dataToLines(data);
		// 不要关闭in, 这不是我的责任
	}

	private void dataToLines(byte[] data) {
		StringBuilder sb = new StringBuilder(32);

		int count = 0;
		for (byte b : data) {
			if (0 == count % 16) {
				sb.append(String.format("%05X: ", count));
			}
			sb.append(String.format("%02X ", b));
			++count;
			if (0 == count % 16) {
				lines.add(sb.toString());
				sb.delete(0, sb.length());
			}
		}
	}
}
